Title: Get the Status of a Twitch Stream

Publish Date: Wed, 01 Feb 2017 09:00:00 +0000

Categories: Uncategorized

Content:

I worked on a site for a friend some time ago and she is a streamer on Twitch. What I wanted to add is a widget in the header that shows her Twitch stream status, so when she is live, if someone goes to the site, they can see that, and eventually check her live Twitch stream.

Knowing if someone is live via the API that Twitch provides is very easy. Let’s check how I did that.



Create an App on Twitch

First of all, from a few months, Twitch requires an app to use any of their API endpoints. Before this switch, you were able to use the endpoint that we are going to use without using an app, but now it’s mandatory to have it.

Go to [ablank href="https://www.twitch.tv/settings/connections"]this page[/ablank] and, at the bottom, create a new app for your site and copy its client ID.

Start Coding

Once you created the app and you have the client ID, you are ready to start coding.
The endpoint that we are going to use is: https://api.twitch.tv/kraken/streams/{stream_name}/?client_id={your_client_id}.

And this is the snippet used to get a boolean value indicating the stream status, true if it’s live, false if it’s not:

https://gist.github.com/SiR-DanieL/65e56f4d5618b4218acf09b8710df9a1

The code is very basic and easy to understand.
At first we create the complete URL, including the channel name and the your app’s client ID.

Then we get the response from the API with wp_remote_get. The API will return an empty body if the streamer is offline, so we just make sure that there are no errors in fetching data from the endpoint and that the response code is 200.

In that case, we check if the response is empty, in which case we return false because the streamer is offline. Otherwise, we just return true ignoring all the data included in the response.

You could also expand the code and return more data, like the streamer name, images from the stream, etc. It’s up to you!

Let's Build a Plugin

On the 21st January 2017 I streamed live on Twitch the development of a WordPress plugin based on this code! You can see the recording of the stream here or on my [ablank href="https://www.youtube.com/c/NicolaMustone"]YouTube channel[/ablank].

https://www.youtube.com/watch?v=WKIZP6mjpfs
